﻿using System;
using System.Web.Mvc;
using TSharp.Core.Mvc.Web;

namespace TSharp.Core.Mvc.Web
{
    /// <summary>
    /// 表示默认情况下已注册的控制器工厂
    /// <para>2010/8/22</para>
    /// 	<para>THINKPADT61</para>
    /// 	<para>tangjingbo</para>
    /// </summary>
    public class TSharpControllerFactory : DefaultControllerFactory
    {
        /// <summary>
        /// 检索指定请求上下文和控制器类型的控制器实例。
        /// </summary>
        /// <param name="requestContext">HTTP 请求的上下文，其中包括 HTTP 上下文和路由数据。</param>
        /// <param name="controllerType">控制器的类型。</param>
        /// <returns>控制器实例。</returns>
        /// <exception cref="T:System.Web.HttpException">
        /// 	<paramref name="controllerType"/> 为 null。</exception>
        /// <exception cref="T:System.ArgumentException">不能分配 <paramref name="controllerType"/>。</exception>
        /// <exception cref="T:System.InvalidOperationException">不能创建 <paramref name="controllerType"/> 的实例。</exception>
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null) return null;

                var controller = base.GetControllerInstance(requestContext, controllerType);
                if (controller is Controller)
                    (controller as Controller).ActionInvoker = MVCControllerActionInvoker.Instance;
                var container = AopContext.Default;
                return container.BuildUp(controller.GetType(), controller) as IController; 
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }
    }
}